<?php
/**
 * Created by PhpStorm.
 * User: LG
 * Date: 2017/8/28
 * Time: 11:55
 */

namespace app\admin\controller;

use app\common\model\ContractEquipment;
use think\Cache;
use think\Controller;
use app\common\model\Contract;
use app\common\model\Customer;
use app\common\model\Equipments;
use app\common\model\Parts;
use app\common\model\Engineers;
use app\common\model\Configuration;
use think\Db;

/*
 *  合同控制器
 *  URL访问区分大小写时：ContractInfo
 *  URL访问不区分大小写时：Contract_Info（或者contract_info）
 */

class Contractinfo extends Base
{

    protected $Contract;

    public function __construct()
    {
        parent::__construct();
        //实例化合同model
        $this->Contract = new Contract();
    }

    /**
     * 将excel时间转换为日期格式
     * @author ligang
     * @param $date
     * @param bool $time
     * @return array|int|string
     * @date 2018/9/5 19:11
     */
    protected function excelTime($date, $time = false)
    {
        if (function_exists('GregorianToJD')) {
            if (is_numeric($date)) {
                $jd = GregorianToJD(1, 1, 1970);
                $gregorian = JDToGregorian($jd + intval($date) - 25569);
                $date = explode('/', $gregorian);
                $date_str = str_pad($date [2], 4, '0', STR_PAD_LEFT)
                    . "-" . str_pad($date [0], 2, '0', STR_PAD_LEFT)
                    . "-" . str_pad($date [1], 2, '0', STR_PAD_LEFT)
                    . ($time ? " 00:00:00" : '');
                return $date_str;
            }
        } else {
            $date = $date > 25568 ? $date + 1 : 25569;
            /*There was a bug if Converting date before 1-1-1970 (tstamp 0)*/
            $ofs = (70 * 365 + 17 + 2) * 86400;
            $date = date("Y-m-d", ($date * 86400) - $ofs) . ($time ? " 00:00:00" : '');
        }
        return $date;
    }

    public function test()
    {
        for ($i = 1;$i<=101;$i++){
            echo rand(pow(10,(18-1)), pow(10,18)-1) .'<br>';
        }
    }

    protected function make_tree($list, $pk, $pid, $child, $root)
    {
        $tree = array();
        $packData = array();
        foreach ($list as $data) {
            $packData[$data[$pk]] = $data;
        }
        foreach ($packData as $key => $val) {
            if ($val[$pid] == $root) {   //代表跟节点
                $tree[] =& $packData[$key];
            } else {
                //找到其父类
                $packData[$val[$pid]][$child][] =& $packData[$key];
            }
        }
        return $tree;
    }

    /**
     * 导入合同
     * @author ligang
     * @return \think\response\Json
     * @throws \Exception
     * @date 2018/9/5 16:49
     */
    public function import()
    {
        $time = time();
        ini_set('max_execution_time', '0');
        header('Content-Type:text/html;charset=utf-8');
        $file = request()->file('file');
        //获取文件信息
        if (!$file) {
            return json(['code' => -1000, 'msg' => '文件上传失败，请重试']);
        }
        $info = $file->move(ROOT_PATH . 'public' . DS . 'customer' . DS . 'new');
        $file_path = ROOT_PATH . 'public' . DS . 'customer' . DS . 'new/' . $info->getSaveName();
        Vendor('phpexcel.phpexcel.Classes.PHPExcel');
        $PHPReader = \PHPExcel_IOFactory::createReaderForFile($file_path);
        $PHPExcel = $PHPReader->load($file_path);
        $sheet = $PHPExcel->getSheet(0);
        $highestRow = $sheet->getHighestRow();
        $highestColumn = $sheet->getHighestColumn();
        //列数验证
        if (strtolower($highestColumn) != 'ak') {
            unlink($file_path);
            return json(['code' => -1000, 'msg' => '列数必须以AK列结束']);
        }
        $data = [];
        for ($rowIndex = 3; $rowIndex <= $highestRow; $rowIndex++) {
            $tmp = [];
            $is_null = false;
            for ($colIndex = 'A'; $colIndex <= 'Z'; $colIndex++) {
                $addr = $colIndex . $rowIndex;
                $cell = $sheet->getCell($addr)->getValue();
                if ($cell instanceof PHPExcel_RichText) {
                    $cell = $cell->__toString();//富文本转换字符串
                }
                if (is_null($cell)) {
                    $is_null = true;
                    $cell = '';
                } else {
                    $is_null = false;
                }
                //转换日期
                if (!is_null($cell) && ($colIndex == 'T' || $colIndex == 'X' || $colIndex == 'Y' || $colIndex == 'AB')) {
                    $cell = $this->excelTime($cell);
                }
                array_push($tmp, trim($cell));
                //到AK列停止读取
                if ($colIndex == 'AK') {
                    break;
                }
            }
            if ($is_null) {
                break;
            }
            array_push($data, $tmp);
        }
        //获取所有客户的身份证和电话
        $client = Db::table('rq_customer')->field('user_id,username,telphone,id_card,employee_id')->select();
        $all_telphone = [];
        $all_id_card = [];
        $all_user_id = [];
        $all_worker = [];
        foreach ($client as $key => $value) {
            if (!empty($value['telphone'])) {
                array_push($all_telphone, $value['telphone']);
            }
            if (!empty($value['id_card'])) {
                array_push($all_id_card, $value['id_card']);
            }
            if (!empty($value['user_id'])) {
                array_push($all_user_id, $value['user_id']);
            }
            if (!empty($value['employee_id'])) {
                $all_worker[$value['employee_id']] = $value;
            }
        }
        //获取所有合同编号
        $pact_number = Db::table('rq_contract')->field('user_id,contract_no')->select();
        $all_number = [];
        $all_pact = [];
        foreach ($pact_number as $key => $value) {
            if (!empty($value['contract_no'])) {
                array_push($all_number, $value['contract_no']);
                $all_pact[$value['contract_no']] = $value;
            }
        }
        //获取所有运营中心和行政中心
        $operation = Db::table('rq_operation_info')->field('o_id,company_name')->select();
        $all_operation = [];
        foreach ($operation as $key => $value) {
            $all_operation[$value['o_id']] = $value['company_name'];
        }
        $administrative_field = '
            rq_administrative_info.a_id,
            rq_administrative_info.company_name,
            rq_administrative_info.province_name,
            rq_administrative_info.city_name,
            rq_administrative_info.area_name,
            rq_administrative_info.province_id,
            rq_administrative_info.city_id,
            rq_administrative_info.area_id,
            rq_administrative_info.operation
        ';
        $administrative = Db::table('rq_administrative_info')->field($administrative_field)->select();
        $all_administrative = [];
        $all_administrative_info = [];
        foreach ($administrative as $key => $value) {
            $all_administrative[$value['a_id']] = $value['company_name'];
            //若存在多个区域，则默认第一个
            $multi_area_id = stripos($value['area_id'], ',');
            $multi_area_name = stripos($value['area_name'], ',');
            if ($multi_area_id !== false && $multi_area_name !== false) {
                $value['area_id'] = substr($value['area_id'], 0, $multi_area_id);
                $value['area_name'] = substr($value['area_name'], 0, $multi_area_name);
            }
            $all_administrative_info[$value['a_id']] = $value;
        }
        //构建系统地址数据数组
        $address = Db::table('rq_areas')->select();
        $address_data = [];
        foreach ($address as $key => $value) {
            if ($value['parent_id'] == 0) {
                $address_tmp = $this->make_tree($address, 'id', 'parent_id', 'child', $value['id']);
                $value['child'] = $address_tmp;
                array_push($address_data, $value);
                continue;
            }
        }
        //客户性质  住房性质
        $nature = [1 => '商用客户', 2 => '家用客户', 3 => '外接包年', 4 => '外接点餐', 5 => '购买客户'];
        $housing_property = [1 => '公租房', 2 => '廉租房', 3 => '租赁', 4 => '购买'];

        //获取所有设备型号
        $equipments = Db::table('rq_equipments')->field('equipments_id,equipments_name')->select();
        $all_equipments = [];
        foreach ($equipments as $key => $value) {
            $all_equipments[$value['equipments_id']] = $value['equipments_name'];
        }

        //组装验证数据
        $user = [];//客户总数据
        $user_admin = [];//客户所属区域总数据
        $pact = [];//合同总数据
        $device = [];//合同设备总数据
        $pact_remark = [];//合同备注总数据
        $pact_log = [];//合同日志总数据

        //设置临时用户ID，确保用户ID不存在的时候去找到合同和用户区域
        $user_id_tmp = 1;
        //设备临时合同ID
        $c_id_tmp = 1;
        try{
            foreach ($data as $key => $value) {
                //客户ID分两种情况，1：存在，说明客户已存在不需要增加客户，2：不存在说明客户不存在，需要增加
                //数据验证
                if (strlen($value[2]) != 18) {
                    unlink($file_path);
                    return json(['code' => -1000, 'msg' => '第' . ($key + 3) . '行客户身份证必须是18位']);
                }
                if (strlen($value[3]) != 11) {
                    unlink($file_path);
                    return json(['code' => -1000, 'msg' => '第' . ($key + 3) . '行客户电话必须是11位']);
                }
                if (strlen($value[16]) != 11) {
                    unlink($file_path);
                    return json(['code' => -1000, 'msg' => '第' . ($key + 3) . '行联系电话必须是11位']);
                }
                //转介绍非必填
                if (strlen($value[6]) > 0 && !in_array($value[6], $all_number)) {
                    unlink($file_path);
                    return json(['code' => -1000, 'msg' => '第' . ($key + 3) . '行转介绍合同编号不存在，合同编号：' . $value[6]]);
                }
                if (in_array($value[12], $all_number)) {
                    unlink($file_path);
                    return json(['code' => -1000, 'msg' => '第' . ($key + 3) . '行合同编号已存在，合同编号：' . $value[12]]);
                }
                if (!isset($all_worker[$value[4]])) {
                    unlink($file_path);
                    return json(['code' => -1000, 'msg' => '第' . ($key + 3) . '行申请人员工编号不存在，员工编号：' . $value[4]]);
                }
                if ($all_worker[$value[4]]['username'] != $value[5]) {
                    unlink($file_path);
                    return json(['code' => -1000, 'msg' => '第' . ($key + 3) . '行申请人姓名与员工编号不匹配，员工姓名：' . $value[5]]);
                }
                $o_id = array_search($value[7], $all_operation);
                if ($o_id === false) {
                    unlink($file_path);
                    return json(['code' => -1000, 'msg' => '第' . ($key + 3) . '行运营中心不存在，运营中心：' . $value[7]]);
                }
                $a_id = array_search($value[8], $all_administrative);
                if ($a_id === false) {
                    unlink($file_path);
                    return json(['code' => -1000, 'msg' => '第' . ($key + 3) . '行行政区域不存在，行政区域：' . $value[8]]);
                }
                $n_id = array_search($value[29], $nature);
                if ($n_id === false) {
                    unlink($file_path);
                    return json(['code' => -1000, 'msg' => '第' . ($key + 3) . '行客户性质不存在，客户性质：' . $value[29]]);
                }
                $h_id = array_search($value[30], $housing_property);
                if ($h_id === false) {
                    unlink($file_path);
                    return json(['code' => -1000, 'msg' => '第' . ($key + 3) . '行住房性质不存在，住房性质：' . $value[30]]);
                }
                if (is_null($value[35])) {
                    unlink($file_path);
                    return json(['code' => -1000, 'msg' => '第' . ($key + 3) . '行装机型号不能为空']);
                }
                //检查设备型号是否存在多台
                if (stripos($value[35], '*') !== false) {
                    $e_tmp = explode('*', $value[35]);
                    $e_id = [];
                    foreach ($e_tmp as $ek => $ev) {
                        if (!empty($ev)) {
                            $e_id_tmp = array_search($ev, $all_equipments);
                            if ($e_id_tmp === false) {
                                unlink($file_path);
                                return json(['code' => -1000, 'msg' => '第' . ($key + 3) . '行装机型号不存在，装机型号：' . $ev]);
                            }
                            array_push($e_id, $e_id_tmp);
                        }
                    }
                } else {
                    $e_id = array_search($value[35], $all_equipments);
                    if ($e_id === false) {
                        unlink($file_path);
                        return json(['code' => -1000, 'msg' => '第' . ($key + 3) . '行装机型号不存在，装机型号：' . $value[35]]);
                    }
                }

                //省市区只要有一个为空则不匹配地址
                $is_address = true;
                if (is_null($value[9]) || is_null($value[10]) || is_null($value[11])) {
                    $is_address = true;
                } else {
                    $address_tmp = [];
                    //只要一个没有匹配上，也不匹配地址
                    foreach ($address_data as $k => $v) {
                        if ($value[9] == $v['area_name']) {
                            //省
                            $province = [
                                'id' => $v['id'],
                                'area_name' => $v['area_name']
                            ];
                            array_push($address_tmp, $province);
                            $is_address = false;
                            foreach ($v['child'] as $kk => $vv) {
                                if ($value[10] == $vv['area_name']) {
                                    //市
                                    $city = [
                                        'id' => $vv['id'],
                                        'area_name' => $vv['area_name']
                                    ];
                                    array_push($address_tmp, $city);
                                    $is_address = false;
                                    foreach ($vv['child'] as $kkk => $vvv) {
                                        if ($value[11] == $vvv['area_name']) {
                                            //区
                                            $area = [
                                                'id' => $vvv['id'],
                                                'area_name' => $vvv['area_name']
                                            ];
                                            array_push($address_tmp, $area);
                                            $is_address = false;
                                            break;
                                        } else {
                                            $is_address = true;
                                        }
                                    }
                                } else {
                                    $is_address = true;
                                }
                            }
                        } else {
                            $is_address = true;
                        }
                    }
                }
                if (empty($value[0])) {
                    if (in_array($value[2], $all_id_card)) {
                        unlink($file_path);
                        return json(['code' => -1000, 'msg' => '第' . ($key + 3) . '行客户身份证已存在']);
                    }
                    if (in_array($value[3], $all_telphone)) {
                        unlink($file_path);
                        return json(['code' => -1000, 'msg' => '第' . ($key + 3) . '行客户电话已存在']);
                    }
                    $user_tmp = [
                        'user_id' => $user_id_tmp,
                        'telphone' => $value[3],
                        'id_card' => $value[2],
                        'username' => $value[1],
                        'province' => $is_address ? $all_administrative_info[$a_id]['province_name'] : $address_tmp[0]['area_name'],
                        'city' => $is_address ? $all_administrative_info[$a_id]['city_name'] : $address_tmp[1]['area_name'],
                        'area' => $is_address ? $all_administrative_info[$a_id]['area_name'] : $address_tmp[2]['area_name'],
                        'province_code' => $is_address ? $all_administrative_info[$a_id]['province_id'] : $address_tmp[0]['id'],
                        'city_code' => $is_address ? $all_administrative_info[$a_id]['city_id'] : $address_tmp[1]['id'],
                        'area_code' => $is_address ? $all_administrative_info[$a_id]['area_id'] : $address_tmp[2]['id'],
                        'user_address' => $value[20],
                        'operation_id' => $o_id,
                        'nature' => $n_id,
                        'housing_property' => $h_id,
                        'add_time' => time()
                    ];
                    array_push($user, $user_tmp);
                    $user_admin_tmp = [
                        'user_id' => $user_id_tmp,
                        'administrative_id' => $a_id,
                    ];
                    array_push($user_admin, $user_admin_tmp);
                } else {
                    if (!in_array($value[0], $all_user_id)) {
                        unlink($file_path);
                        return json(['code' => -1000, 'msg' => '第' . ($key + 3) . '行客户ID不存在']);
                    }
                }

                //合同
                $pact_tmp = [
                    'c_id' => $c_id_tmp,
                    'user_id' => empty($value[0]) ? $user_id_tmp : $value[0],
                    'introducer_id' => strlen($value[6]) > 0 ? $all_pact[$value[6]]['user_id'] : 0,
                    'applicant' => $all_worker[$value[4]]['user_id'],
                    'administrative_id' => $a_id,
                    'operation_id' => $o_id,
                    'province' => $is_address ? $all_administrative_info[$a_id]['province_name'] : $address_tmp[0]['area_name'],
                    'city' => $is_address ? $all_administrative_info[$a_id]['city_name'] : $address_tmp[1]['area_name'],
                    'area' => $is_address ? $all_administrative_info[$a_id]['area_name'] : $address_tmp[2]['area_name'],
                    'province_code' => $is_address ? $all_administrative_info[$a_id]['province_id'] : $address_tmp[0]['id'],
                    'city_code' => $is_address ? $all_administrative_info[$a_id]['city_id'] : $address_tmp[1]['id'],
                    'area_code' => $is_address ? $all_administrative_info[$a_id]['area_id'] : $address_tmp[2]['id'],
                    'contract_no' => $value[12],
                    'water_pressure' => $value[13],
                    'receipt' => $value[14],
                    'contract_money' => $value[15],
                    'phone' => $value[16],
                    'contact_person' => $value[17],
                    'corporate_name' => $value[18],
                    'installed_time' => strtotime($value[19]),
                    'address' => $value[20],
                    'for_core_cost' => $value[21],
                    'for_core_cycle' => $value[22],
                    'for_core_time' => strtotime($value[23]),
                    'recent_time' => strtotime($value[24]),
                    'for_core_number' => $value[25],
                    'moving_machine_number' => $value[26],
                    'exire_date' => strtotime($value[27]),
                    'renew_date' => $value[28],
                    'add_time' => time(),
                    'nature' => $n_id,
                    'housing_property' => $h_id,
                    'eq_count' => empty($value[30]) ? 1 : $value[30],
                    'contract_type' => ($value[32] == '是') ? 1 : 0,
                    'is_explain' => ($value[33] == '无') ? 2 : 1,
                    'is_special' => ($value[34] == '否') ? 2 : 1
                ];
                array_push($pact, $pact_tmp);
                //合同备注
                $pact_remark_tmp = [
                    'contract_no' => $value[12],
                    'remark' => $value[36],
                    'add_time' => time(),
                ];
                array_push($pact_remark, $pact_remark_tmp);
                //合同日志
                $pact_log_tmp = [
                    'contract_id' => $c_id_tmp,
                    'do_id' => 0,
                    'do_type' => 1,
                    'terminal_type' => 0,
                    'do_time' => time(),
                    'old_value' => '',
                    'new_value' => '合同，合同编号：' . $value[12],
                ];
                array_push($pact_log, $pact_log_tmp);

                //合同设备
                if (is_array($e_id)) {
                    foreach ($e_id as $ekk => $evv) {
                        $device_tmp = [
                            'contract_id' => $c_id_tmp,
                            'equipments_id' => $evv,
                            'equipments_number' => randEquipmentsNumber(),
                            'equipments_address' => $value[20],
                            'addtime' => time(),
                        ];
                        array_push($device, $device_tmp);
                    }
                } else {
                    $device_tmp = [
                        'contract_id' => $c_id_tmp,
                        'equipments_id' => $e_id,
                        'equipments_number' => randEquipmentsNumber(),
                        'equipments_address' => $value[20],
                        'addtime' => time(),
                    ];
                    array_push($device, $device_tmp);
                }

                //递增临时用户ID
                $user_id_tmp++;
                $c_id_tmp++;
            }
        }catch (\Exception $exception){
//            echo $exception;
            return json(['code' => -1000, 'msg' => '服务器异常，请联系管理员','data'=>$exception->getMessage().' 本次耗时：'.(time() - $time).'s']);
        }

        unlink($file_path);
        Db::startTrans();
        try {
            //先判断用户
            if (!empty($user) && !empty($user_admin)) {
                foreach ($user as $key => $value) {
                    $user_id = $value['user_id'];
                    unset($value['user_id']);
                    $user_insert_id = Db::table('rq_customer')->insertGetId($value);
                    foreach ($user_admin as $k => $v) {
                        if ($v['user_id'] == $user_id) {
                            $user_admin[$k]['user_id'] = $user_insert_id;
                        }
                    }
                    foreach ($pact as $kk => $vv) {
                        if ($vv['user_id'] == $user_id) {
                            $pact[$kk]['user_id'] = $user_insert_id;
                        }
                    }
                }
            }
            foreach ($pact as $key => $value) {
                $c_id = $value['c_id'];
                unset($value['c_id']);
                $pact_insert_id = Db::table('rq_contract')->insertGetId($value);
                foreach ($device as $k => $v) {
                    if ($v['contract_id'] == $c_id) {
                        $device[$k]['contract_id'] = $pact_insert_id;
                    }
                }
                foreach ($pact_log as $kk => $vv) {
                    if ($vv['contract_id'] == $c_id) {
                        $pact_log[$kk]['contract_id'] = $pact_insert_id;
                    }
                }
            }

            //批量插入
            Db::table('rq_contract_remark')->insertAll($pact_remark);
            Db::table('rq_contract_equipment')->insertAll($device);
            Db::table('rq_contract_log')->insertAll($pact_log);
            Db::table('rq_customer_administrative_center')->insertAll($user_admin);

            Db::commit();
            return json(['code' => 1000, 'msg' => '导入完成，请对导入数据逐一检查.','data'=>'本次耗时：'.(time() - $time).'s']);
        } catch (\Exception $e) {
            Db::rollback();
            return json(['code' => -1000, 'msg' => '导入失败，请稍后再试.','data'=>$e->getMessage().' 本次耗时：'.(time() - $time).'s']);
        }
    }

    public function getExport()
    {
        return $this->fetch('contract/export');
    }

    /**
     * 导出含关系的合同
     * @author ligang
     * @date 2018/9/5 15:19
     */
    public function exportExcelRelation()
    {
        ini_set("max_execution_time", "0");
        ob_end_clean();//清除缓冲区,避免乱码
        ob_start();
        header('Content-Type:text/html;charset=utf-8');

        $start_time = input('get.start_time');
        $end_time = input('get.end_time');

        if (!empty($start_time) && !empty($end_time)) {
            $where = [
                'rq_contract.installed_time' => ['between', [strtotime(date('Y-m-d 00:00:00', strtotime($start_time))), strtotime(date('Y-m-d 23:59:59', strtotime($end_time)))]]
            ];
        } else {
            $this->error('请选择导出时间段');
        }

        try {
            $join = [
                ['rq_customer', 'rq_contract.user_id = rq_customer.user_id', 'LEFT'],
                ['rq_contract_rank', 'rq_contract.contract_no = rq_contract_rank.contract_no', 'LEFT'],
                ['rq_contract_remark', 'rq_contract.contract_no = rq_contract_remark.contract_no', 'LEFT']
            ];
            $field = '  rq_contract.phone,
                    rq_contract_rank.*,
                    rq_contract.contract_id,
                    rq_contract.contact_person,
                    rq_contract.corporate_name,
                    rq_contract.contract_no,
                    rq_contract.address,
                    rq_contract.installed_time,
                    rq_contract.contract_status,
                    rq_contract.housing_property,
                    rq_contract.province,
                    rq_contract.city,
                    rq_contract.area,
                    rq_contract.contract_type,
                    rq_contract.contract_status,
                    rq_contract.introducer_id,
                    rq_contract.applicant,
                    rq_contract.for_core_cost,
                    rq_customer.username,
                    rq_customer.user_type,
                    rq_contract_remark.remark,
                    rq_contract.nature';
            $where['rq_contract.is_delete'] = 0;
            $data = Db::table('rq_contract')->where($where)->field($field)->join($join)->group('rq_contract.contract_no')->select();
            $e_join = [
                ['rq_equipments', 'rq_contract_equipment.equipments_id = rq_equipments.equipments_id', 'LEFT']
            ];
            $e_field = 'rq_equipments.equipments_name';
            $e_where = [
                'state' => 1,
                'rq_contract_equipment.is_delete' => 0
            ];
            foreach ($data as $key => $value) {
                if (!empty($value['introducer_id'])) {
                    $data[$key]['introducer_name'] = Db::table('rq_customer')->where(['user_id' => $value['introducer_id']])->field('username')->find()['username'];
                } else {
                    $data[$key]['introducer_name'] = '';
                }

                if (!empty($value['applicant'])) {
                    $data[$key]['applicant_name'] = Db::table('rq_customer')->where(['user_id' => $value['applicant']])->field('username')->find()['username'];
                } else {
                    $data[$key]['applicant_name'] = '';
                }

                $data[$key]['installed_time'] = date('Y-m-d', $value['installed_time']);
                switch ($value['contract_status']) {//1.正常,2.拆机冻结,3.退机冻结,4.合同到期停止服务,5.拒绝付费停止服务,6.买断停止服务，7无效
                    case 1:
                        $data[$key]['contract_status'] = '正常';
                        break;
                    case 2:
                        $data[$key]['contract_status'] = '拆机冻结';
                        break;
                    case 3:
                        $data[$key]['contract_status'] = '退机冻结';
                        break;
                    case 4:
                        $data[$key]['contract_status'] = '合同到期停止服务';
                        break;
                    case 5:
                        $data[$key]['contract_status'] = '拒绝付费停止服务';
                        break;
                    case 6:
                        $data[$key]['contract_status'] = '买断停止服务';
                        break;
                    case 7:
                        $data[$key]['contract_status'] = '无效';
                        break;
                }
                switch ($value['nature']) {//客户性质(1.商用客户,2.家用客户,3外接包年,4.外接点餐,5.购买客户)'
                    case 1:
                        $data[$key]['nature'] = '商用客户';
                        $data[$key]['contact_person'] = $value['corporate_name'];
                        break;
                    case 2:
                        $data[$key]['nature'] = '家用客户';
                        break;
                    case 3:
                        $data[$key]['nature'] = '外接包年';
                        break;
                    case 4:
                        $data[$key]['nature'] = '外接点餐';
                        break;
                    case 5:
                        $data[$key]['nature'] = '购买客户';
                        break;
                }
                switch ($value['housing_property']) {//住房性质(1.公租房,2.廉租房,3.租赁,4.购买)
                    case 1:
                        $data[$key]['housing_property'] = '公租房';
                        break;
                    case 2:
                        $data[$key]['housing_property'] = '廉租房';
                        break;
                    case 3:
                        $data[$key]['housing_property'] = '租赁';
                        break;
                    case 4:
                        $data[$key]['housing_property'] = '购买';
                        break;
                }

                $data[$key]['contract_type'] = $value['contract_type'] ? '是' : '否';

                $data[$key]['equipment'] = '';
                $e_where['contract_id'] = $value['contract_id'];
                $equipment = Db::table('rq_contract_equipment')->where($e_where)->join($e_join)->field($e_field)->select();
                foreach ($equipment as $k => $v) {
                    $data[$key]['equipment'] .= $v['equipments_name'] . ',';
                }
                $data[$key]['equipment'] = substr($data[$key]['equipment'], 0, -1);
            }
            $this->exportExcel2($data, $where);
        } catch (\Exception $e) {
            if (config('app_debug')) {
                echo $e;
                return false;
            }
            $this->error('服务器错误');
        }
    }

    public function Excel()
    {
        ini_set("max_execution_time", "0");
        ob_end_clean();//清除缓冲区,避免乱码
        ob_start();
        header('Content-Type:text/html;charset=utf-8');

        $start_time = input('get.start_time');
        $end_time = input('get.end_time');

        if (!empty($start_time) && !empty($end_time)) {
            $where = [
                'rq_contract.installed_time' => ['between', [strtotime(date('Y-m-d 00:00:00', strtotime($start_time))), strtotime(date('Y-m-d 23:59:59', strtotime($end_time)))]]
            ];
        } else {
            $this->error('请选择导出时间段');
        }
        try {
            $join = [
                ['rq_customer', 'rq_contract.user_id = rq_customer.user_id', 'LEFT'],
                ['rq_contract_remark', 'rq_contract.contract_no = rq_contract_remark.contract_no', 'LEFT']
            ];
            $field = '  rq_contract.phone,
                    rq_contract.contract_id,
                    rq_contract.contact_person,
                    rq_contract.corporate_name,
                    rq_contract.contract_no,
                    rq_contract.address,
                    rq_contract.installed_time,
                    rq_contract.contract_status,
                    rq_contract.housing_property,
                    rq_contract.province,
                    rq_contract.city,
                    rq_contract.area,
                    rq_contract.contract_type,
                    rq_contract.contract_status,
                    rq_contract.introducer_id,
                    rq_contract.applicant,
                    rq_contract.for_core_cost,
                    rq_customer.username,
                    rq_customer.user_type,
                    rq_contract_remark.remark,
                    rq_contract.nature';
            $where['rq_contract.is_delete'] = 0;
            $data = Db::table('rq_contract')->where($where)->field($field)->join($join)->group('contract_no')->select();
            $e_join = [
                ['rq_equipments', 'rq_contract_equipment.equipments_id = rq_equipments.equipments_id', 'LEFT']
            ];
            $e_field = 'rq_equipments.equipments_name';
            $e_where = [
                'state' => 1,
                'rq_contract_equipment.is_delete' => 0
            ];
            foreach ($data as $key => $value) {
                if (!empty($value['introducer_id'])) {
                    $data[$key]['introducer_name'] = Db::table('rq_customer')->where(['user_id' => $value['introducer_id']])->field('username')->find()['username'];
                } else {
                    $data[$key]['introducer_name'] = '';
                }

                if (!empty($value['applicant'])) {
                    $data[$key]['applicant_name'] = Db::table('rq_customer')->where(['user_id' => $value['applicant']])->field('username')->find()['username'];
                } else {
                    $data[$key]['applicant_name'] = '';
                }

                $data[$key]['installed_time'] = date('Y-m-d', $value['installed_time']);
                switch ($value['contract_status']) {//1.正常,2.拆机冻结,3.退机冻结,4.合同到期停止服务,5.拒绝付费停止服务,6.买断停止服务，7无效
                    case 1:
                        $data[$key]['contract_status'] = '正常';
                        break;
                    case 2:
                        $data[$key]['contract_status'] = '拆机冻结';
                        break;
                    case 3:
                        $data[$key]['contract_status'] = '退机冻结';
                        break;
                    case 4:
                        $data[$key]['contract_status'] = '合同到期停止服务';
                        break;
                    case 5:
                        $data[$key]['contract_status'] = '拒绝付费停止服务';
                        break;
                    case 6:
                        $data[$key]['contract_status'] = '买断停止服务';
                        break;
                    case 7:
                        $data[$key]['contract_status'] = '无效';
                        break;
                }
                switch ($value['nature']) {//客户性质(1.商用客户,2.家用客户,3外接包年,4.外接点餐,5.购买客户)'
                    case 1:
                        $data[$key]['nature'] = '商用客户';
                        $data[$key]['contact_person'] = $value['corporate_name'];
                        break;
                    case 2:
                        $data[$key]['nature'] = '家用客户';
                        break;
                    case 3:
                        $data[$key]['nature'] = '外接包年';
                        break;
                    case 4:
                        $data[$key]['nature'] = '外接点餐';
                        break;
                    case 5:
                        $data[$key]['nature'] = '购买客户';
                        break;
                }
                switch ($value['housing_property']) {//住房性质(1.公租房,2.廉租房,3.租赁,4.购买)
                    case 1:
                        $data[$key]['housing_property'] = '公租房';
                        break;
                    case 2:
                        $data[$key]['housing_property'] = '廉租房';
                        break;
                    case 3:
                        $data[$key]['housing_property'] = '租赁';
                        break;
                    case 4:
                        $data[$key]['housing_property'] = '购买';
                        break;
                }

                $data[$key]['contract_type'] = $value['contract_type'] ? '是' : '否';

                $data[$key]['equipment'] = '';
                $e_where['contract_id'] = $value['contract_id'];
                $equipment = Db::table('rq_contract_equipment')->where($e_where)->join($e_join)->field($e_field)->select();
                foreach ($equipment as $k => $v) {
                    $data[$key]['equipment'] .= $v['equipments_name'] . ',';
                }
                $data[$key]['equipment'] = substr($data[$key]['equipment'], 0, -1);
            }
            $this->exportExcel($data, $where);
        } catch (\Exception $e) {
            if (config('app_debug')) {
                echo $e;
                return false;
            }
            $this->error('服务器错误');
        }
    }

    /**
     * 导出合同关系
     * @author ligang
     * @param $data
     * @param $where
     * @return string
     * @throws \Exception
     * @date 2018/9/5 15:25
     */
    public function exportExcel2($data, $where)
    {
        if (!is_array($data)) {
            return "数据格式错误";
        }
        $title = '';
        if (isset($where['installed_time']) && !empty($where['installed_time'])) {
            $title .= date('Y-m-d H:i:s', $where['installed_time'][1][0]);
            $title .= ' 至 ';
            $title .= date('Y-m-d H:i:s', $where['installed_time'][1][1]);
        }
        $title .= ' 合同信息';
        $filename = '合同信息' . '-' . date('Y-m-d H:i:s', time()) . ".xls";
        Vendor('phpexcel.phpexcel.Classes.PHPExcel');
        $PHPExcel = new \PHPExcel();
        //设置信任
        $PHPExcel->getProperties()->setCreator("ctos")
            ->setLastModifiedBy("ctos")
            ->setTitle("Office 2007 XLSX Test Document")
            ->setSubject("Office 2007 XLSX Test Document")
            ->setDescription("Test document for Office 2007 XLSX, generated using PHP classes.")
            ->setKeywords("office 2007 openxml php")
            ->setCategory("Test result file");

        //设置标题
        $PHPExcel->getActiveSheet()->setCellValue('A1', $title);
        $PHPExcel->getActiveSheet()->getRowDimension(1)->setRowHeight(35);
        $PHPExcel->getActiveSheet()->getRowDimension(2)->setRowHeight(22);
        $PHPExcel->getActiveSheet()->getRowDimension(3)->setRowHeight(20);
        //合并单元格
        $PHPExcel->getActiveSheet()->mergeCells('A1:V1');
        //设置列宽
        $PHPExcel->getActiveSheet()->getColumnDimension('A')->setWidth(20);
        $PHPExcel->getActiveSheet()->getColumnDimension('B')->setWidth(25);
        $PHPExcel->getActiveSheet()->getColumnDimension('C')->setWidth(30);
        $PHPExcel->getActiveSheet()->getColumnDimension('D')->setWidth(50);
        $PHPExcel->getActiveSheet()->getColumnDimension('E')->setWidth(20);
        $PHPExcel->getActiveSheet()->getColumnDimension('F')->setWidth(20);
        $PHPExcel->getActiveSheet()->getColumnDimension('G')->setWidth(20);
        $PHPExcel->getActiveSheet()->getColumnDimension('H')->setWidth(30);
        $PHPExcel->getActiveSheet()->getColumnDimension('I')->setWidth(30);
        $PHPExcel->getActiveSheet()->getColumnDimension('J')->setWidth(30);
        $PHPExcel->getActiveSheet()->getColumnDimension('K')->setWidth(30);
        $PHPExcel->getActiveSheet()->getColumnDimension('L')->setWidth(30);
        $PHPExcel->getActiveSheet()->getColumnDimension('M')->setWidth(30);
        //设置表头
        $PHPExcel->getActiveSheet()->setCellValue('A2', '姓名');
        $PHPExcel->getActiveSheet()->setCellValue('B2', '联系电话');
        $PHPExcel->getActiveSheet()->setCellValue('C2', '合同编号');
        $PHPExcel->getActiveSheet()->setCellValue('D2', '机型');
        $PHPExcel->getActiveSheet()->setCellValue('E2', '装机地址');
        $PHPExcel->getActiveSheet()->setCellValue('F2', '合同状态');
        $PHPExcel->getActiveSheet()->setCellValue('G2', '房屋类型');
        $PHPExcel->getActiveSheet()->setCellValue('H2', '是否升级VIP');
        $PHPExcel->getActiveSheet()->setCellValue('I2', '准经销商');
        $PHPExcel->getActiveSheet()->setCellValue('J2', '转介绍');
        $PHPExcel->getActiveSheet()->setCellValue('K2', '装机时间');
        $PHPExcel->getActiveSheet()->setCellValue('L2', '服务金额');
        $PHPExcel->getActiveSheet()->setCellValue('M2', '合同备注');
        $PHPExcel->getActiveSheet()->setCellValue('N2', '申请人');
        $PHPExcel->getActiveSheet()->setCellValue('O2', '转介绍');
        $PHPExcel->getActiveSheet()->setCellValue('P2', '直推人');
        $PHPExcel->getActiveSheet()->setCellValue('Q2', '经销商');
        $PHPExcel->getActiveSheet()->setCellValue('R2', '星级经销');
        $PHPExcel->getActiveSheet()->setCellValue('S2', '2星级经销');
        $PHPExcel->getActiveSheet()->setCellValue('T2', '5星级经销');
        $PHPExcel->getActiveSheet()->setCellValue('U2', '10星级经销');
        $PHPExcel->getActiveSheet()->setCellValue('V2', '20星级经销');
        //设置字体样式
        $PHPExcel->getActiveSheet()->getStyle('A1')->getFont()->setName('黑体');
        $PHPExcel->getActiveSheet()->getStyle('A1')->getFont()->setSize(20);
        $PHPExcel->getActiveSheet()->getStyle('A1')->getFont()->setBold(true);
        $PHPExcel->getActiveSheet()->getStyle('A2:V2')->getFont()->setName('微软雅黑');
        $PHPExcel->getActiveSheet()->getStyle('A2:V2')->getFont()->setSize(14);
        $PHPExcel->getActiveSheet()->getStyle('A2:V2')->getFont()->setBold(true);
        $PHPExcel->getActiveSheet()->getStyle('A')->getAlignment()->setVertical(\PHPExcel_Style_Alignment::VERTICAL_CENTER);
        $PHPExcel->getActiveSheet()->getStyle('A1')->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
        $PHPExcel->getActiveSheet()->getStyle('A1')->getAlignment()->setVertical(\PHPExcel_Style_Alignment::VERTICAL_CENTER);
        foreach ($data as $k => $v) {
            //设置单元格值
            $PHPExcel->getActiveSheet()->setCellValue('A' . ($k + 3), $v['contact_person']);
            $PHPExcel->getActiveSheet()->setCellValue('B' . ($k + 3), ' ' . $v["phone"]);
            $PHPExcel->getActiveSheet()->setCellValue('C' . ($k + 3), ' ' . $v["contract_no"]);
            $PHPExcel->getActiveSheet()->setCellValue('D' . ($k + 3), $v['equipment']);
            $PHPExcel->getActiveSheet()->setCellValue('E' . ($k + 3), $v['province'] . $v['city'] . $v['area'] . $v['address']);
            $PHPExcel->getActiveSheet()->setCellValue('F' . ($k + 3), $v['contract_status']);
            $PHPExcel->getActiveSheet()->setCellValue('G' . ($k + 3), $v['housing_property']);
            $PHPExcel->getActiveSheet()->setCellValue('H' . ($k + 3), $v['contract_type']);
            $PHPExcel->getActiveSheet()->setCellValue('I' . ($k + 3), $v['applicant_name']);
            $PHPExcel->getActiveSheet()->setCellValue('J' . ($k + 3), $v['introducer_name']);
            $PHPExcel->getActiveSheet()->setCellValue('K' . ($k + 3), $v['installed_time']);
            $PHPExcel->getActiveSheet()->setCellValue('L' . ($k + 3), $v['for_core_cost'] . '元');
            $PHPExcel->getActiveSheet()->setCellValue('M' . ($k + 3), $v['remark']);
            $PHPExcel->getActiveSheet()->setCellValue('N' . ($k + 3), empty($v['apply_name']) ? '' : $v['apply_name'] . '(' . $v['apply_id'] . ')');
            $PHPExcel->getActiveSheet()->setCellValue('O' . ($k + 3), empty($v['push_apply_name']) ? '' : $v['push_apply_name'] . '(' . $v['push_apply_id'] . ')');
            $PHPExcel->getActiveSheet()->setCellValue('P' . ($k + 3), empty($v['push_name']) ? '' : $v['push_name'] . '(' . $v['push_id'] . ')');
            $PHPExcel->getActiveSheet()->setCellValue('Q' . ($k + 3), empty($v['manage_name']) ? '' : $v['manage_name'] . '(' . $v['manage_id'] . ')');
            $PHPExcel->getActiveSheet()->setCellValue('R' . ($k + 3), empty($v['star_manage_name']) ? '' : $v['star_manage_name'] . '(' . $v['star_manage_id'] . ')');
            $PHPExcel->getActiveSheet()->setCellValue('S' . ($k + 3), empty($v['two_manage_name']) ? '' : $v['two_manage_name'] . '(' . $v['two_manage_id'] . ')');
            $PHPExcel->getActiveSheet()->setCellValue('T' . ($k + 3), empty($v['five_manage_name']) ? '' : $v['five_manage_name'] . '(' . $v['five_manage_id'] . ')');
            $PHPExcel->getActiveSheet()->setCellValue('U' . ($k + 3), empty($v['ten_manage_name']) ? '' : $v['ten_manage_name'] . '(' . $v['ten_manage_id'] . ')');
            $PHPExcel->getActiveSheet()->setCellValue('V' . ($k + 3), empty($v['twenty_manage_name']) ? '' : $v['twenty_manage_name'] . '(' . $v['twenty_manage_id'] . ')');
            //设置居中
            $PHPExcel->getActiveSheet()->getStyle('A2:V' . ($k + 3))->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);

            //垂直居中
            $PHPExcel->getActiveSheet()->getStyle('A' . $k)->getAlignment()->setVertical(\PHPExcel_Style_Alignment::VERTICAL_CENTER);
            $PHPExcel->getActiveSheet()->getStyle('B' . $k)->getAlignment()->setVertical(\PHPExcel_Style_Alignment::VERTICAL_CENTER);
            $PHPExcel->getActiveSheet()->getStyle('C' . $k)->getAlignment()->setVertical(\PHPExcel_Style_Alignment::VERTICAL_CENTER);
            $PHPExcel->getActiveSheet()->getStyle('D' . $k)->getAlignment()->setVertical(\PHPExcel_Style_Alignment::VERTICAL_CENTER);
            $PHPExcel->getActiveSheet()->getStyle('E' . $k)->getAlignment()->setVertical(\PHPExcel_Style_Alignment::VERTICAL_CENTER);
            $PHPExcel->getActiveSheet()->getStyle('F' . $k)->getAlignment()->setVertical(\PHPExcel_Style_Alignment::VERTICAL_CENTER);
            $PHPExcel->getActiveSheet()->getStyle('G' . $k)->getAlignment()->setVertical(\PHPExcel_Style_Alignment::VERTICAL_CENTER);
            $PHPExcel->getActiveSheet()->getStyle('H' . $k)->getAlignment()->setVertical(\PHPExcel_Style_Alignment::VERTICAL_CENTER);
            $PHPExcel->getActiveSheet()->getStyle('I' . $k)->getAlignment()->setVertical(\PHPExcel_Style_Alignment::VERTICAL_CENTER);
            $PHPExcel->getActiveSheet()->getStyle('J' . $k)->getAlignment()->setVertical(\PHPExcel_Style_Alignment::VERTICAL_CENTER);
            $PHPExcel->getActiveSheet()->getStyle('K' . $k)->getAlignment()->setVertical(\PHPExcel_Style_Alignment::VERTICAL_CENTER);
            $PHPExcel->getActiveSheet()->getStyle('L' . $k)->getAlignment()->setVertical(\PHPExcel_Style_Alignment::VERTICAL_CENTER);
            $PHPExcel->getActiveSheet()->getStyle('M' . $k)->getAlignment()->setVertical(\PHPExcel_Style_Alignment::VERTICAL_CENTER);
            $PHPExcel->getActiveSheet()->getStyle('N' . $k)->getAlignment()->setVertical(\PHPExcel_Style_Alignment::VERTICAL_CENTER);
            $PHPExcel->getActiveSheet()->getStyle('O' . $k)->getAlignment()->setVertical(\PHPExcel_Style_Alignment::VERTICAL_CENTER);
            $PHPExcel->getActiveSheet()->getStyle('P' . $k)->getAlignment()->setVertical(\PHPExcel_Style_Alignment::VERTICAL_CENTER);
            $PHPExcel->getActiveSheet()->getStyle('Q' . $k)->getAlignment()->setVertical(\PHPExcel_Style_Alignment::VERTICAL_CENTER);
            $PHPExcel->getActiveSheet()->getStyle('R' . $k)->getAlignment()->setVertical(\PHPExcel_Style_Alignment::VERTICAL_CENTER);
            $PHPExcel->getActiveSheet()->getStyle('S' . $k)->getAlignment()->setVertical(\PHPExcel_Style_Alignment::VERTICAL_CENTER);
            $PHPExcel->getActiveSheet()->getStyle('T' . $k)->getAlignment()->setVertical(\PHPExcel_Style_Alignment::VERTICAL_CENTER);
            $PHPExcel->getActiveSheet()->getStyle('U' . $k)->getAlignment()->setVertical(\PHPExcel_Style_Alignment::VERTICAL_CENTER);
            $PHPExcel->getActiveSheet()->getStyle('V' . $k)->getAlignment()->setVertical(\PHPExcel_Style_Alignment::VERTICAL_CENTER);

        }
        $PHPSheet = $PHPExcel->getActiveSheet();
        //给当前活动sheet设置名称
        $PHPSheet->setTitle("合同信息");
        //创建生成的格式
        $PHPWriter = \PHPExcel_IOFactory::createWriter($PHPExcel, "Excel5");
        //下载下来的表格名
        ob_end_clean();
        header('content-Type:application/vnd.ms-excel;charset=utf-8');
        header('Content-Disposition: attachment;filename="' . $filename . '"');
        header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
        header('Cache-Control: max-age=0');
        $PHPWriter->save("php://output");


    }

    public function exportExcel($data, $where)
    {
        if (!is_array($data)) {
            return "数据格式错误";
        }
        $title = '';
        if (isset($where['installed_time']) && !empty($where['installed_time'])) {
            $title .= date('Y-m-d H:i:s', $where['installed_time'][1][0]);
            $title .= ' 至 ';
            $title .= date('Y-m-d H:i:s', $where['installed_time'][1][1]);
        }
        $title .= ' 合同信息';
        $filename = '合同信息' . '-' . date('Y-m-d H:i:s', time()) . ".xls";
        Vendor('phpexcel.phpexcel.Classes.PHPExcel');
        $PHPExcel = new \PHPExcel();
        //设置信任
        $PHPExcel->getProperties()->setCreator("ctos")
            ->setLastModifiedBy("ctos")
            ->setTitle("Office 2007 XLSX Test Document")
            ->setSubject("Office 2007 XLSX Test Document")
            ->setDescription("Test document for Office 2007 XLSX, generated using PHP classes.")
            ->setKeywords("office 2007 openxml php")
            ->setCategory("Test result file");

        //设置标题
        $PHPExcel->getActiveSheet()->setCellValue('A1', $title);
        $PHPExcel->getActiveSheet()->getRowDimension(1)->setRowHeight(35);
        $PHPExcel->getActiveSheet()->getRowDimension(2)->setRowHeight(22);
        $PHPExcel->getActiveSheet()->getRowDimension(3)->setRowHeight(20);
        //合并单元格
        $PHPExcel->getActiveSheet()->mergeCells('A1:M1');
        //设置列宽
        $PHPExcel->getActiveSheet()->getColumnDimension('A')->setWidth(20);
        $PHPExcel->getActiveSheet()->getColumnDimension('B')->setWidth(25);
        $PHPExcel->getActiveSheet()->getColumnDimension('C')->setWidth(30);
        $PHPExcel->getActiveSheet()->getColumnDimension('D')->setWidth(50);
        $PHPExcel->getActiveSheet()->getColumnDimension('E')->setWidth(20);
        $PHPExcel->getActiveSheet()->getColumnDimension('F')->setWidth(20);
        $PHPExcel->getActiveSheet()->getColumnDimension('G')->setWidth(20);
        $PHPExcel->getActiveSheet()->getColumnDimension('H')->setWidth(30);
        $PHPExcel->getActiveSheet()->getColumnDimension('I')->setWidth(30);
        $PHPExcel->getActiveSheet()->getColumnDimension('J')->setWidth(30);
        $PHPExcel->getActiveSheet()->getColumnDimension('K')->setWidth(30);
        $PHPExcel->getActiveSheet()->getColumnDimension('L')->setWidth(30);
        $PHPExcel->getActiveSheet()->getColumnDimension('M')->setWidth(30);
        //设置表头
        $PHPExcel->getActiveSheet()->setCellValue('A2', '姓名');
        $PHPExcel->getActiveSheet()->setCellValue('B2', '联系电话');
        $PHPExcel->getActiveSheet()->setCellValue('C2', '合同编号');
        $PHPExcel->getActiveSheet()->setCellValue('D2', '机型');
        $PHPExcel->getActiveSheet()->setCellValue('E2', '装机地址');
        $PHPExcel->getActiveSheet()->setCellValue('F2', '合同状态');
        $PHPExcel->getActiveSheet()->setCellValue('G2', '房屋类型');
        $PHPExcel->getActiveSheet()->setCellValue('H2', '是否升级VIP');
        $PHPExcel->getActiveSheet()->setCellValue('I2', '准经销商');
        $PHPExcel->getActiveSheet()->setCellValue('J2', '转介绍');
        $PHPExcel->getActiveSheet()->setCellValue('K2', '装机时间');
        $PHPExcel->getActiveSheet()->setCellValue('L2', '服务金额');
        $PHPExcel->getActiveSheet()->setCellValue('M2', '合同备注');
        //设置字体样式
        $PHPExcel->getActiveSheet()->getStyle('A1')->getFont()->setName('黑体');
        $PHPExcel->getActiveSheet()->getStyle('A1')->getFont()->setSize(20);
        $PHPExcel->getActiveSheet()->getStyle('A1')->getFont()->setBold(true);
        $PHPExcel->getActiveSheet()->getStyle('A2:M2')->getFont()->setName('微软雅黑');
        $PHPExcel->getActiveSheet()->getStyle('A2:M2')->getFont()->setSize(14);
        $PHPExcel->getActiveSheet()->getStyle('A2:M2')->getFont()->setBold(true);
        $PHPExcel->getActiveSheet()->getStyle('A')->getAlignment()->setVertical(\PHPExcel_Style_Alignment::VERTICAL_CENTER);
        $PHPExcel->getActiveSheet()->getStyle('A1')->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
        $PHPExcel->getActiveSheet()->getStyle('A1')->getAlignment()->setVertical(\PHPExcel_Style_Alignment::VERTICAL_CENTER);
        foreach ($data as $k => $v) {
            //设置单元格值
            $PHPExcel->getActiveSheet()->setCellValue('A' . ($k + 3), $v['username']);
            $PHPExcel->getActiveSheet()->setCellValue('B' . ($k + 3), ' ' . $v["phone"]);
            $PHPExcel->getActiveSheet()->setCellValue('C' . ($k + 3), ' ' . $v["contract_no"]);
            $PHPExcel->getActiveSheet()->setCellValue('D' . ($k + 3), $v['equipment']);
            $PHPExcel->getActiveSheet()->setCellValue('E' . ($k + 3), $v['province'] . $v['city'] . $v['area'] . $v['address']);
            $PHPExcel->getActiveSheet()->setCellValue('F' . ($k + 3), $v['contract_status']);
            $PHPExcel->getActiveSheet()->setCellValue('G' . ($k + 3), $v['housing_property']);
            $PHPExcel->getActiveSheet()->setCellValue('H' . ($k + 3), $v['contract_type']);
            $PHPExcel->getActiveSheet()->setCellValue('I' . ($k + 3), $v['applicant_name']);
            $PHPExcel->getActiveSheet()->setCellValue('J' . ($k + 3), $v['introducer_name']);
            $PHPExcel->getActiveSheet()->setCellValue('K' . ($k + 3), $v['installed_time']);
            $PHPExcel->getActiveSheet()->setCellValue('L' . ($k + 3), $v['for_core_cost'] . '元');
            $PHPExcel->getActiveSheet()->setCellValue('M' . ($k + 3), $v['remark']);
            //设置居中
            $PHPExcel->getActiveSheet()->getStyle('A2:M' . ($k + 3))->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);

            //垂直居中
            $PHPExcel->getActiveSheet()->getStyle('A' . $k)->getAlignment()->setVertical(\PHPExcel_Style_Alignment::VERTICAL_CENTER);
            $PHPExcel->getActiveSheet()->getStyle('B' . $k)->getAlignment()->setVertical(\PHPExcel_Style_Alignment::VERTICAL_CENTER);
            $PHPExcel->getActiveSheet()->getStyle('C' . $k)->getAlignment()->setVertical(\PHPExcel_Style_Alignment::VERTICAL_CENTER);
            $PHPExcel->getActiveSheet()->getStyle('D' . $k)->getAlignment()->setVertical(\PHPExcel_Style_Alignment::VERTICAL_CENTER);
            $PHPExcel->getActiveSheet()->getStyle('E' . $k)->getAlignment()->setVertical(\PHPExcel_Style_Alignment::VERTICAL_CENTER);
            $PHPExcel->getActiveSheet()->getStyle('F' . $k)->getAlignment()->setVertical(\PHPExcel_Style_Alignment::VERTICAL_CENTER);
            $PHPExcel->getActiveSheet()->getStyle('G' . $k)->getAlignment()->setVertical(\PHPExcel_Style_Alignment::VERTICAL_CENTER);
            $PHPExcel->getActiveSheet()->getStyle('H' . $k)->getAlignment()->setVertical(\PHPExcel_Style_Alignment::VERTICAL_CENTER);
            $PHPExcel->getActiveSheet()->getStyle('I' . $k)->getAlignment()->setVertical(\PHPExcel_Style_Alignment::VERTICAL_CENTER);
            $PHPExcel->getActiveSheet()->getStyle('J' . $k)->getAlignment()->setVertical(\PHPExcel_Style_Alignment::VERTICAL_CENTER);
            $PHPExcel->getActiveSheet()->getStyle('K' . $k)->getAlignment()->setVertical(\PHPExcel_Style_Alignment::VERTICAL_CENTER);
            $PHPExcel->getActiveSheet()->getStyle('L' . $k)->getAlignment()->setVertical(\PHPExcel_Style_Alignment::VERTICAL_CENTER);
            $PHPExcel->getActiveSheet()->getStyle('M' . $k)->getAlignment()->setVertical(\PHPExcel_Style_Alignment::VERTICAL_CENTER);

        }
        $PHPSheet = $PHPExcel->getActiveSheet();
        //给当前活动sheet设置名称
        $PHPSheet->setTitle("合同信息");
        //创建生成的格式
        $PHPWriter = \PHPExcel_IOFactory::createWriter($PHPExcel, "Excel5");
        //下载下来的表格名
        ob_end_clean();
        header('content-Type:application/vnd.ms-excel;charset=utf-8');
        header('Content-Disposition: attachment;filename="' . $filename . '"');
        header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
        header('Cache-Control: max-age=0');
        $PHPWriter->save("php://output");


    }

    /**
     * 合同列表
     * @author ligang
     * @Request array    $request     GET   搜索条件(一维数组)
     * @return array
     */
    public function index()
    {
        Cache::clear();
        //处理条件
        $request = input('');
        $where = array();
        $search = array(
            'contact_person' => '',
            'contract_no' => '',
            'id_card' => ''
        );
        foreach ($request as $key => $value) {
            $search[$key] = $value;
            if (empty($value)) {
                continue;
            }
            if ($key == 'contact_person') {
                $where['username'] = ['like', '%' . $value . '%'];
                continue;
            }
            if ($key == 'operation_id') {
                $where['rq_contract.' . $key] = $value;
                continue;
            }
            if ($key == 'administrative_id') {
                $where['rq_contract.' . $key] = $value;
                continue;
            }
            if ($key == 'address') {
                $where['rq_contract.' . $value] = ['like', '%' . $value . '%'];
                continue;
            }
            $where[$key] = $value;
        }
        //获取数据
        $data = $this->Contract->selectPage($where);

        $EquipmentNumberWhere = [
            'is_delete' => 0,
            'state' => 1
        ];
        foreach ($data['data'] as $key => $value) {
            //获取设备台数
            $EquipmentNumberWhere['contract_id'] = $value['contract_id'];
            $EquipmentNumberWhere['state'] = 1;
            $EquipmentNumberWhere['is_delete'] = 0;
            $data['data'][$key]['EquipmentNumber'] = $this->Contract->getEquipmentNumber($EquipmentNumberWhere);
        }

        //获取运营中心
        $operation = $this->Contract->selectOperationInfo();
        //获取行政中心
        $administrative = $this->Contract->selectAdministrativeInfo();
        //模板赋值
        $this->assign('Nowpage', $data['page']['currentPage']); //当前页
        $this->assign('allpage', $data['page']['lastPage']); //总页数
        $this->assign('count', $data['page']['count']);//总条数
        $this->assign('search', $search);
        $this->assign('operation', $operation);
        $this->assign('administrative', $administrative);
        $this->assign('data', $data['data']);
        if (input('get.page')) {
            return json($data);
        }
        //渲染模板
        return $this->fetch("/contract/agreement");
    }

    /**
     * 合同详情
     * @author ligang
     * @Request contract_id             int    GET   合同ID
     * @return array
     */
    public function details()
    {
        Cache::clear();
        //检验get参数
        if (input('?get.contract_id')) {
            //获取参数并强制转换为int型
            $contract_id = input('get.contract_id/d');
        } else {
            return json(array('code' => 0, 'msg' => '缺少必要参数'));
        }

        $join = [
            ['rq_customer', 'rq_contract.user_id = rq_customer.user_id'],
            ['rq_contract_remark', 'rq_contract_remark.contract_no = rq_contract.contract_no', 'LEFT']
        ];
        $field = '
            rq_customer.employee_id,
            rq_customer.username,
            rq_customer.telphone,
            rq_customer.add_time,
            rq_customer.account_status,
            rq_customer.remark,
            rq_customer.user_address,
            rq_customer.user_type,
            rq_customer.province,
            rq_customer.city,
            rq_customer.area,
            rq_customer.birthday,
            rq_contract.contract_no,
            rq_contract.contract_id,
            rq_contract.introducer_id,
            rq_contract.applicant,
            rq_contract.receipt,
            rq_contract.water_pressure,
            rq_contract.contract_money,
            rq_contract.nature,
            rq_contract.contract_type,
            rq_contract.province as ht_province,
            rq_contract.city as ht_city,
            rq_contract.area as ht_area,
            rq_contract.address,
            rq_contract.original_parts,
            rq_contract.installed_time,
            rq_contract.recent_time,
            rq_contract.for_core_cost,
            rq_contract.for_core_cycle,
            rq_contract.for_core_time,
            rq_contract.moving_machine_number,
            rq_contract.renew_date,
            rq_contract.for_core_number,
            rq_contract.administrative_id,
            rq_contract.corporate_name,
            rq_contract.housing_property,
            rq_contract.exire_date,
            rq_contract_remark.remark as contract_remark,
            rq_customer.is_entry
            ';
        //获取数据
        $data = $this->Contract->details(['contract_id' => $contract_id], $join, $field);

        //转换客户状态
        foreach ($data as $key => $value) {
            if ($key == 'account_status') {
                if ($value == 1) {
                    $data[$key] = "正常";
                } else {
                    $data[$key] = "冻结";
                }
                continue;
            }
            if ($key == 'contract_type') {
                if ($value == 0) {
                    $data[$key] = "未升级VIP";
                } else {
                    $data[$key] = "已升级VIP";
                }
                continue;
            }
            if ($key == 'user_type') {
                if ($value == 1) {
                    $data[$key] = "普通用户";
                } else {
                    $data[$key] = "VIP用户";
                }
                continue;
            }
            if ($key == 'exire_date') {
                $data[$key] = date('Y-m-d', $value);
                continue;
            }
            if ($key == 'add_time') {
                $data[$key] = date('Y-m-d H:i:s', $value);
                continue;
            }
            if ($key == 'birthday') {
                $data[$key] = date('Y-m-d', $value);
                continue;
            }
            if ($key == 'installed_time') {
                $data[$key] = date('Y-m-d', $value);
                continue;
            }
            if ($key == 'recent_time') {
                $data[$key] = date('Y-m-d', $value);
                continue;
            }
            if ($key == 'for_core_time') {
                $data[$key] = date('Y-m-d', $value);
                continue;
            }
            if ($key == 'renew_date') {
                $data[$key] = date('Y-m-d', $value);
                continue;
            }
            if ($key == 'housing_property') {
                if ($value == 1) {
                    $data[$key] = "公租房";
                } elseif ($value == 2) {
                    $data[$key] = "廉租房";
                } elseif ($value == 3) {
                    $data[$key] = "租赁";
                } else {
                    $data[$key] = "购买";
                }
                continue;
            }
            if ($key == 'nature') {
                //1.商用客户,2.家用客户,3外接包年,4.外接点餐,5.购买客户
                if ($value == 1) {
                    $data[$key] = "商用客户";
                } elseif ($value == 2) {
                    $data[$key] = "家用客户";
                } elseif ($value == 3) {
                    $data[$key] = "外接包年";
                } elseif ($value == 4) {
                    $data[$key] = "外接点餐";
                } else {
                    $data[$key] = "购买客户";
                }
                continue;
            }
        }
        //判断是否是员工
        if ($data['is_entry'] == 1) {
            $data['is_entry'] = "是";
            $data['personnel_number'] = $data['employee_id'];
        } else {
            $data['is_entry'] = "否";
            $data['personnel_number'] = "";
        }

        //获取推荐人
        $Customer = new Customer();
        $data['introducer_id'] = $Customer->selectOne(['user_id' => $data['introducer_id']])[0]['username'];
        $applicant = $Customer->selectOne(['user_id' => $data['applicant']])[0];
        $data['applicant'] = $applicant['username'];
        $data['applicant_number'] = $applicant['employee_id'];

        //获取设备台数
        $data['EquipmentNumber'] = $this->Contract->getEquipmentNumber(['contract_id' => $contract_id, 'state' => 1, 'rq_contract_equipment.is_delete' => 0]);
        //获取设备记录
        $Equipment_join = [
            ['rq_equipments', 'rq_contract_equipment.equipments_id = rq_equipments.equipments_id'],
        ];
        //查询设备字段
        $Equipment_field = 'rq_equipments.equipments_name,
                            rq_contract_equipment.id,
                            rq_contract_equipment.equipments_id,
                            rq_contract_equipment.equipments_number,
                            rq_contract_equipment.equipments_address,
                            rq_contract_equipment.moving_machine_number
                            ';
        $data['equipment'] = $this->Contract->contractEquipment(['contract_id' => $contract_id, 'state' => 1, 'rq_contract_equipment.is_delete' => 0], $Equipment_join, $Equipment_field);
        $newArr = [];
        foreach ($data['equipment'] as $key => $value) {
            $data['equipment'][$key]['Remark'] = $this->Contract->equipmentsRemark(['contract_equipment_id' => $value['id']]);
            for ($i = 1; $i <= 8; $i++) {
                if ($i == 1 || $i == 6) {
                    continue;
                }
                $record = $this->Contract->equipmentRecord($i, ['equipment_id' => $value['id']]);
                if ($record) {
                    foreach ($record as $rk => $rv) {
                        switch ($i) {
                            case 1:
                                $type = "新装";
                                break;
                            case 2:
                                $type = "维修";
                                break;
                            case 3:
                                $type = "换芯";
                                break;
                            case 4:
                                $type = "拆机";
                                break;
                            case 5:
                                $type = "移机";
                                break;
                            case 6:
                                $type = "续费";
                                break;
                            case 7:
                                $type = "换芯+维修";
                                break;
                            case 8:
                                $type = "续费+维修";
                                break;
                            default:
                                $type = "未知类型";
                        }
                        $record[$rk]['type'] = $type;
                        $data['equipment'][$key]['record'][] = $record[$rk];
                    }
                }
            }
        }
//        dump($data);
        //合同操作记录
        $ContractLogWhere['contract_id'] = $contract_id;
        $ContractLog = $this->Contract->getContractLog($ContractLogWhere, [], '');
        foreach ($ContractLog as $clk => $clv) {
            $ContractLog[$clk]['do_time'] = date('Y-m-d H:i:s', $clv['do_time']);
            switch ($clv['do_type']) {
                case 1:
                    $ContractLog[$clk]['do_type'] = "新增";
                    break;
                case 2:
                    $ContractLog[$clk]['do_type'] = "删除";
                    break;
                case 3:
                    $ContractLog[$clk]['do_type'] = "修改";
                    break;
                case 4:
                    $ContractLog[$clk]['do_type'] = "解绑";
                    break;
            }
        }
        foreach ($ContractLog as $key => $value) {
            switch ($value['terminal_type']) {
                //总后台
                case 0:
                    if ($value['do_id'] == 0) {
                        $ContractLog[$key]['name'] = '系统';
                        $ContractLog[$key]['title'] = '系统';
                        break;
                    }
                    $findUserJoin = [
                        ['rq_admin_auth_group', 'rq_admin_user.groupid = rq_admin_auth_group.id']
                    ];
                    $findUserWhere = [
                        'rq_admin_user.id' => $value['do_id']
                    ];
                    $findUserField = 'rq_admin_user.name,rq_admin_auth_group.title';
                    $admin_user = $this->Contract->findUser('admin_user', $findUserWhere, $findUserJoin, $findUserField);
                    $ContractLog[$key]['name'] = $admin_user['name'];
                    $ContractLog[$key]['title'] = $admin_user['title'];
                    break;
                //运营中心
                case 1:
                    $findUserJoin = [
                        ['rq_operation_auth_group', 'rq_operation_user.groupid = rq_operation_auth_group.id']
                    ];
                    $findUserWhere = [
                        'rq_operation_user.id' => $value['do_id']
                    ];
                    $findUserField = 'rq_operation_user.name,rq_operation_auth_group.title';
                    $admin_user = $this->Contract->findUser('operation_user', $findUserWhere, $findUserJoin, $findUserField);
                    $ContractLog[$key]['name'] = $admin_user['name'];
                    $ContractLog[$key]['title'] = $admin_user['title'];
                    break;
                //行政区域
                case 2:
                    $findUserJoin = [
                        ['rq_administrative_auth_group', 'rq_administrative_user.groupid = rq_administrative_auth_group.id']
                    ];
                    $findUserWhere = [
                        'rq_administrative_user.id' => $value['do_id']
                    ];
                    $findUserField = 'rq_administrative_user.name,rq_administrative_auth_group.title';
                    $admin_user = $this->Contract->findUser('administrative_user', $findUserWhere, $findUserJoin, $findUserField);
                    $ContractLog[$key]['name'] = $admin_user['name'];
                    $ContractLog[$key]['title'] = $admin_user['title'];
                    break;
            }
        }
        //获取合同原始配件
        $PartsObj = new Parts();
        $PartsWhere = [
            'contract_id' => $contract_id,
            'is_original' => 1,
            'rq_equipments_parts.is_delete' => 0
        ];
        $PartsJoin = [
            ['rq_parts', 'rq_equipments_parts.parts_id = rq_parts.parts_id']
        ];
        $PartsField = 'parts_name,parts_number';
        $Parts = $PartsObj->getContractParts($PartsWhere, $PartsField, $PartsJoin);
        //追加原始配件
        $data['original_parts'] = $Parts;

        $data['ContractLog'] = $ContractLog;
        $this->assign('data', $data);
        //查询设备
        $equipments = new Equipments();
        $equipmentsInfo = $equipments->getList();
        $this->view->equipmentsinfo = json_encode($equipmentsInfo);
        //渲染模板
        return $this->fetch("contract/details");

    }

    /*
     *  获取设备操作记录
     *  @author 李港
     *  @param int  $id                     合同设备关联ID
     *  @param int  $equipments_number      设备编号
     *  @param int  $page                   页数
     *  @return array|json
     */
    public function getEquipmentRecord()
    {
        //获取合同设备关联ID
        $id = input('?get.id') ? input('get.id') : false;
        $equipments_number = input('?get.equipments_number') ? input('get.equipments_number') : false;
        $page = input('?get.page') ? input('get.page') : 1;
        if (!$id || !$equipments_number) {
            return ['code' => 0, 'msg' => '缺少必要参数'];
        }
        $recordData = [];
        for ($i = 1; $i <= 8; $i++) {
            $record = $this->Contract->equipmentRecord($i, ['equipment_id' => $id]);
            if ($record) {
                foreach ($record as $rk => $rv) {
                    switch ($i) {
                        case 1:
                            $type = "新装";
                            break;
                        case 2:
                            $type = "维修";
                            break;
                        case 3:
                            $type = "换芯";
                            break;
                        case 4:
                            $type = "拆机";
                            break;
                        case 5:
                            $type = "移机";
                            break;
                        case 6:
                            $type = "续费";
                            break;
                        case 7:
                            $type = "换芯+维修";
                            break;
                        case 8:
                            $type = "续费+维修";
                            break;
                        default:
                            $type = "未知类型";
                    }
                    $record[$rk]['type'] = $type;
                    $recordData[] = $record[$rk];
                }
            }
        }
        $Engineer = new Engineers();
        $ContractEquipment = new ContractEquipment();
        $EngineerField = 'engineers_name';
        $EquipmentsField = 'equipments_address';
        foreach ($recordData as $key => $value) {
            $recordData[$key]['equipments_number'] = $equipments_number;
            //操作人
            if ($value['repair_id'] == 0) {
                $recordData[$key]['repair_id'] = '系统';
            } else {
                $recordData[$key]['repair_id'] = $Engineer->getEngineerInfo(['engineers_id' => $value['repair_id']], $EngineerField)['engineers_name'];
            }
            //设备地址
            $recordData[$key]['address'] = $ContractEquipment->findEquipmentsData(['id' => $id], [], $EquipmentsField)['equipments_address'];
            //操作时间
            foreach (array_keys($recordData[$key]) as $k => $v) {
                if (strpos($v, 'time')) {
                    $recordData[$key]['do_date'] = date('Y-m-d H:i:s', $value[$v]);
                    unset($recordData[$key][$v]);
                    continue;
                }
            }
        }
        $Configuration = new Configuration();
        //每页显示数目
        $listRows = intval($Configuration->getkey('pagesize'));
        //总条数
        $recordTotal = count($recordData);
        //总页数
        $recordTotalPage = ceil($recordTotal / $listRows);
        if ($page == 1) {
            $start = 0;
        } else {
            $start = ($page - 1) * $listRows;
        }
        $data = array_slice($recordData, $start, $listRows);
        $data['data'] = $data;
        $data['page']['currentPage'] = $page;
        $data['page']['lastPage'] = $recordTotalPage;
        $data['page']['count'] = $recordTotal;
        if (input('?get.page')) {
            return json($data);
        }
    }

    /*
     *  获取合同操作记录
     */
    public function getAllContractLog()
    {
        $contract_id = input('?get.contract_id') ? input('get.contract_id/d') : false;
        if (!$contract_id) {
            return ['code' => 0, 'msg' => '缺少必要参数'];
        }
        $ContractLogWhere['contract_id'] = $contract_id;
        $page = 1;
        $page_number = '';
        $ContractLog = $this->Contract->getContractLog($ContractLogWhere, [], '', $page, $page_number);
        foreach ($ContractLog as $clk => $clv) {
            $ContractLog[$clk]['do_time'] = date('Y-m-d H:i:s', $clv['do_time']);
            switch ($clv['do_type']) {
                case 1:
                    $ContractLog[$clk]['do_type'] = "新增";
                    break;
                case 2:
                    $ContractLog[$clk]['do_type'] = "删除";
                    break;
                case 3:
                    $ContractLog[$clk]['do_type'] = "修改";
                    break;
                case 4:
                    $ContractLog[$clk]['do_type'] = "解绑";
                    break;
            }
        }
        foreach ($ContractLog as $key => $value) {
            switch ($value['terminal_type']) {
                //总后台
                case 0:
                    if ($value['do_id'] == 0) {
                        $ContractLog[$key]['name'] = '系统';
                        $ContractLog[$key]['title'] = '系统';
                        break;
                    }
                    $findUserJoin = [
                        ['rq_admin_auth_group', 'rq_admin_user.groupid = rq_admin_auth_group.id']
                    ];
                    $findUserWhere = [
                        'rq_admin_user.id' => $value['do_id']
                    ];
                    $findUserField = 'rq_admin_user.name,rq_admin_auth_group.title';
                    $admin_user = $this->Contract->findUser('admin_user', $findUserWhere, $findUserJoin, $findUserField);
                    $ContractLog[$key]['name'] = $admin_user['name'];
                    $ContractLog[$key]['title'] = $admin_user['title'];
                    break;
                //行政区域
                case 1:
                    $findUserJoin = [
                        ['rq_administrative_auth_group', 'rq_administrative_user.groupid = rq_administrative_auth_group.id']
                    ];
                    $findUserWhere = [
                        'rq_administrative_user.id' => $value['do_id']
                    ];
                    $findUserField = 'rq_administrative_user.name,rq_administrative_auth_group.title';
                    $admin_user = $this->Contract->findUser('administrative_user', $findUserWhere, $findUserJoin, $findUserField);
                    $ContractLog[$key]['name'] = $admin_user['name'];
                    $ContractLog[$key]['title'] = $admin_user['title'];
                    break;
                //运营中心
                case 2:
                    $findUserJoin = [
                        ['rq_operation_auth_group', 'rq_operation_user.groupid = rq_operation_auth_group.id']
                    ];
                    $findUserWhere = [
                        'rq_operation_user.id' => $value['do_id']
                    ];
                    $findUserField = 'rq_operation_user.name,rq_operation_auth_group.title';
                    $admin_user = $this->Contract->findUser('operation_user', $findUserWhere, $findUserJoin, $findUserField);
                    $ContractLog[$key]['name'] = $admin_user['name'];
                    $ContractLog[$key]['title'] = $admin_user['title'];
                    break;
            }
        }
        foreach ($ContractLog as $k => &$v) {
            $arr_key = array_keys($v);
            foreach ($arr_key as $ak => $av) {
                if (empty($v[$av])) {
                    $v[$av] = '';
                }
            }
        }
        $data['code'] = 1;
        $data['data'] = $ContractLog;
        return json($data);
    }

    /*
     *  获取合同图片
     *  @author ligang
     *  @Request contract_id             int    GET   合同ID
     *  @return array
     */
    public function contractImages()
    {
        $id = input('?get.id') ? input('get.id') : false;
        if (!$id) {
            return ['code' => 0, 'msg' => '非法请求'];
        }
        $data = $this->Contract->contractImg(['contract_id' => $id], 'contract_imgs');
        if (empty($data['contract_imgs'])) {
            return ['code' => 0, 'msg' => '没有相关附件信息'];
        }
        if (is_null(json_decode($data['contract_imgs']))) {
            return ['code' => 0, 'msg' => '数据格式错误'];
        }
        $imgUrl = json_decode($data['contract_imgs']);
        $array = [
            'code' => 1,
            'data' => $imgUrl
        ];
        return json($array);
    }

    /*
     * 添加设备备注
     * @author ligang
     * @Request equipments_id             int    GET   设备ID
     */
    public function addRemark()
    {
        $id = input('?get.id') ? input('get.id') : false;
        if (!$id) {
            return ['code' => 0, 'msg' => '缺少必要参数'];
        }
        $contract_id = input('?get.contract_id') ? input('get.contract_id') : false;
        if (!$contract_id) {
            return ['code' => 0, 'msg' => '缺少必要参数'];
        }
        $equipments_id = input('?get.equipments_id') ? input('get.equipments_id/d') : false;
        if (!$equipments_id) {
            return ['code' => 0, 'msg' => '缺少必要参数'];
        }
        $remark = input('?get.remark') ? input('get.remark') : false;
        if (!$remark) {
            return ['code' => 0, 'msg' => '请输入备注信息'];
        }
        //获取合同设备关联的ID
        $data['contract_equipment_id'] = $id;
        $data['equipments_remark'] = trim($remark);
        $Equipments_add = $this->Contract->addEquipmentsRemark($data);
        $where['id'] = $id;
        $Equipment = $this->Contract->contractEquipment($where, [], 'equipments_number')[0];

        $Log = [
            'contract_id' => $contract_id,
            'do_type' => 1,
            'terminal_type' => 0,
            'new_value' => $Equipment['equipments_number'] . "设备备注：" . $remark,
        ];
        if ($Equipments_add) {
            $this->Contract->addContractLog($Log);
            return ['code' => 1, 'msg' => '添加成功'];
        } else {
            return ['code' => 0, 'msg' => '添加失败'];
        }
    }

    /*
     * 解绑设备
     * @author ligang
     * @Request equipments_id             int    GET   设备ID
     */
    public function unBindEquipments()
    {
        $id = input('get.id');
        $ContractEquipmentObj = new ContractEquipment();
        $EquipmentsInfo = $ContractEquipmentObj->getEquipmentsData(['id' => $id])[0];
        if ($EquipmentsInfo) {
            $result = $ContractEquipmentObj->edit(['id' => $id], ['state' => 0]);
            if ($result) {
                $Log = [
                    'contract_id' => $EquipmentsInfo['contract_id'],
                    'do_type' => 4,
                    'terminal_type' => 0,
                    'old_value' => '设备编号：' . $EquipmentsInfo['equipments_number'],
                    'new_value' => ''
                ];
                $this->Contract->addContractLog($Log);

                //判断合同下是否存在设备
                $ContractEquipmentDataWhere = [
                    'contract_id' => $EquipmentsInfo['contract_id'],
                    'state' => 1,
                    'is_delete' => 0,
                ];
                $ContractEquipmentData = $ContractEquipmentObj->getEquipmentsData($ContractEquipmentDataWhere);
                if (empty($ContractEquipmentData)) {
                    $Contract = new Contract();
                    $ContractWhere = [
                        'contract_id' => $EquipmentsInfo['contract_id']
                    ];
                    $ContractData = [
                        'contract_status' => 7,
                        'update_time' => time()
                    ];
                    $Contract->updateContract($ContractWhere, $ContractData);
                    $ContractLog = [
                        'contract_id' => $EquipmentsInfo['contract_id'],
                        'do_type' => 3,
                        'terminal_type' => 0,
                        'old_value' => '',
                        'new_value' => '合同下不存在设备，改为无效合同'
                    ];
                    $this->Contract->addContractLog($ContractLog);
                }
                return ['code' => 1, 'msg' => '解绑成功'];
            } else {
                return ['code' => 0, 'msg' => '解绑失败'];
            }
        } else {
            return ['code' => 0, 'msg' => '设备不存在'];
        }

    }

    /*
     * 修改设备
     * @author ligang
     * @Request equipments_id             int    GET   设备ID
     */
    public function editEquipments()
    {
        $contract_id = input('?get.contract_id') ? input('get.contract_id') : false;
        $id = input('?get.id') ? input('get.id') : false;
        $equipments_id = input('?get.equipments_id') ? input('get.equipments_id/d') : false;
        $equipments_name = input('?get.equipments_name') ? trim(input('get.equipments_name')) : false;
        $equipments_number = !empty(input('param.equipments_number')) ? trim(input('param.equipments_number')) : false;
        $equipmentsObj = new ContractEquipment();
        $equipmentsInfo = $equipmentsObj->getOne(['id' => $equipments_id]);
        if (!$equipmentsInfo) {
            return ['code' => 0, 'msg' => '非法操作'];
        }

        if (!$equipments_id || !$contract_id || !$id) {
            return ['code' => 0, 'msg' => '缺少必要参数'];
        }
        if (!$equipments_name) {
            return ['code' => 0, 'msg' => '请输入设备型号'];
        }
        if (!$equipments_number) {
            return ['code' => 0, 'msg' => '请输入设备编号'];
        }
        if (strlen($equipments_number) != 10) {
            return ['code' => 0, 'msg' => '设备编号为10位纯数字'];
        }


        $ContractEquipmentObj = new ContractEquipment();
        $EquipmentObj = new Equipments();
        $checkNumber = $ContractEquipmentObj->getEquipmentsData(['equipments_number' => $equipments_number]);
        if ($checkNumber) {
            return ['code' => 0, 'msg' => '设备编号已存在'];
        }
        $where['id'] = $id;
        $join = [
            ['rq_equipments', 'rq_contract_equipment.equipments_id = rq_equipments.equipments_id']
        ];
        $equipments = $ContractEquipmentObj->getEquipmentsData($where, $join, 'equipments_name,rq_contract_equipment.equipments_number')[0];
        $newWhere = [
            'equipments_id' => $equipments_name
        ];
        $newEquipmentsName = $EquipmentObj->selectOne($newWhere);
        $updateData['id'] = $id;
        $updateData['equipments_id'] = $equipments_name;
        $updateData['equipments_number'] = $equipments_number;
        $updateData['uptime'] = time();
        $result = $ContractEquipmentObj->updateEquipmentsData([], $updateData);
        if ($result) {
            $data['old_value'] = '设备ID:' . $equipments['equipments_name'] . ';' . '设备编号:' . $equipments['equipments_number'];
            $data['new_value'] = '设备ID:' . $newEquipmentsName['equipments_name'] . ';' . '设备编号:' . $updateData['equipments_number'];
            $data['contract_id'] = $contract_id;
            $data['do_type'] = 3;
            $data['terminal_type'] = 0;
            $this->Contract->addContractLog($data);
            return ['code' => 1, 'msg' => '修改成功'];
        } else {
            return ['code' => 0, 'msg' => '修改失败'];
        }


    }
    /*
     *  合同图片
     *  @author ligang
     *  @Request contract_id             int    GET   合同ID
     *  @return array
     */
    /*
    public function contractImages()
    {
        $id = input('?get.id')?input('get.id'):false;
        if (!$id){
            return ['code'=>0,'msg'=>'非法请求'];
        }
        $data = $this->Contract->contractImg(['contract_id'=>$id],'contract_imgs');
        if (is_null(json_decode($data['contract_imgs']))){
            return ['code'=>0,'msg'=>'数据格式错误'];
        }
        $imgUrl = json_decode($data['contract_imgs']);
        $array = [
            'code'=>1,
            'data'=>$imgUrl
        ];
        return  json($array);
    }
    */

    /**
     * 修改合同     回显
     * @author ligang
     * @Request contract_id             int    GET   合同ID
     * @return array
     */
    public function edit()
    {
        //检验get参数
        if (input('?get.contract_id')) {
            //获取参数并强制转换为int型
            $where['contract_id'] = input('get.contract_id/d');
        } else {
            return json(array('code' => 0, 'msg' => '缺少必要参数'));
        }
        $data = $this->Contract->selectOne($where);
        $this->assign('data' . $data);
    }

    /**
     * 修改合同     操作
     * @author ligang
     * @Request contract_id             int    GET   合同ID
     * @return array
     */
    public function doEdit()
    {

    }

    /**
     * 删除合同     逻辑删除
     * @author ligang
     * @Request contract_id             int    GET   合同ID
     * @return array
     */
    public function delete()
    {
        //检验get参数
        if (input('?get.data')) {
            //获取参数并强制转换为int型
            $contract_id = input('')['data'];
        } else {
            return json(array('code' => 0, 'msg' => '缺少必要参数'));
        }

        foreach ($contract_id as $key => $value) {
            if ($value == 'on') {
                continue;
            }

            $checkData = $this->Contract->selectOne(array('contract_id' => intval($value)));

            if (empty($checkData)) {
                return json(array('code' => 0, 'msg' => "删除失败"));
            }
            $res = $this->Contract->deleteOne($value);
            if ($res === false) {
                return json(array('code' => 0, 'msg' => '删除失败'));
            }
        }
        return json(array('code' => 1, 'msg' => '删除成功'));
    }

    /**
     * 根据运营中心获取行政中心
     * @author ligang
     * @Request operation_id             int    GET   合同ID
     * @return array
     */
    public function selectAdministrative()
    {
        $where = array();
        if (input('get.operation/d')) {
            $where['operation'] = input('get.operation/d');
        }
        $administrative = $this->Contract->selectAdministrativeInfo($where);
        return $administrative;
    }


}
